package com.bondmatch.demo.controller;

import com.bondmatch.demo.model.Result;
import com.bondmatch.demo.utils.DefaultResponseBody;
import com.bondmatch.demo.model.TransRequest;
import com.bondmatch.demo.service.MatchResultService;
import com.bondmatch.demo.service.TransRequestService;
import com.bondmatch.demo.utils.MatchAlgorithm;
import com.bondmatch.demo.utils.Pager;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.*;

@Controller
@CrossOrigin
public class TransRequestController {
    @Resource
    private TransRequestService transRequestService;
    @Resource
    private MatchResultService matchResultService;


    /**
     * 选择模式进行匹配，返回首页
     *
     * @param matchType:匹配方式:1对应random, 2对应timeFirst, 3对应priceFirst
     * @param idList:所选择数据              id
     * @return
     */
    @RequestMapping("/bond_match/match")
    @ResponseBody
    public DefaultResponseBody match(@RequestParam("matchType") Integer matchType, @RequestParam("transId") int[] idList) {
        DefaultResponseBody defaultResponseBody = new DefaultResponseBody();
        List<TransRequest> BuyRequestList = new ArrayList<>();
        List<TransRequest> SellRequestList = new ArrayList<>();

        /*根据买卖分组*/
        for (int i = 0; i < idList.length; i++) {
            TransRequest transRequest = transRequestService.selectByPrimaryKey(idList[i]);
            //判断买卖，进行分组
            if (transRequest.getType() == 0) {
                BuyRequestList.add(transRequest);
            } else {
                SellRequestList.add(transRequest);
            }
        }
        /*判断所选数据*/
        if (BuyRequestList.isEmpty()) {
            defaultResponseBody.setCode(500);
            defaultResponseBody.setMessage("请至少选择一条买入请求");
            defaultResponseBody.setData("500");
            return defaultResponseBody;
        } else if (SellRequestList.isEmpty()) {
            defaultResponseBody.setCode(500);
            defaultResponseBody.setMessage("请至少选择一条卖出请求");
            defaultResponseBody.setData("500");
            return defaultResponseBody;
        } else {

            Set<String> bondCodes = new HashSet<>();
            for (TransRequest transRequest : BuyRequestList) {
                bondCodes.add(transRequest.getBondCode());
            }
            for (TransRequest transRequest : SellRequestList) {
                //买卖列表中有同一债券
                if (bondCodes.contains(transRequest.getBondCode())) {
                    //调用匹配算法，返回匹配成功的id二维数
                    ArrayList<Result> matchArray = MatchAlgorithm.transationMatch(matchType, BuyRequestList, SellRequestList);
                    //数据整合
                    matchResultService.combineTrans(matchArray);
                    defaultResponseBody.setCode(200);
                    defaultResponseBody.setMessage("匹配成功");
                    defaultResponseBody.setData(null);
                    return defaultResponseBody;
                }
            }
        }
        defaultResponseBody.setCode(500);
        defaultResponseBody.setData("500");
        defaultResponseBody.setMessage("匹配失败，买卖无同一债券");
        return defaultResponseBody;
    }

    //导入excel数据
    @RequestMapping("/bond_match/add")
    @ResponseBody
    public DefaultResponseBody uploadExcelFile(MultipartFile excelFile) throws Exception {
//      public DefaultResponseBody add() throws Exception {//测试用
        DefaultResponseBody resultMap = new DefaultResponseBody();
//        String filePath = "C:\\Users\\zixin.nie\\Desktop\\春芽项目\\交易信息表.xls";
//        File file = new File(filePath);
//        FileInputStream fileInputStream = new FileInputStream(file);
        // MockMultipartFile(String name, @Nullable String originalFilename, @Nullable String contentType, InputStream contentStream)
        // 其中originalFilename,String contentType 旧名字，类型  可为空
        // ContentType.APPLICATION_OCTET_STREAM.toString() 需要使用HttpClient的包
//        MultipartFile excelFile = new MockMultipartFile(file.getName(),file.getName(),null,fileInputStream);
        if (excelFile.isEmpty()) {
            resultMap.setCode(500);
            resultMap.setMessage("文件为空。");
            return resultMap;
        } else {
            String fileName = excelFile.getOriginalFilename();//获取文件名
            InputStream in = excelFile.getInputStream();//获取文件输入流
            return transRequestService.importExcel(in, fileName);
        }
    }

    /**
     * 首页 交易请求展示
     *
     * @param pageNum
     * @param pageSize
     * @return
     * @throws Exception
     */
    @RequestMapping("/bond_match")
    @ResponseBody
    public DefaultResponseBody getTransRequest(int pageNum, int pageSize) throws Exception {
        DefaultResponseBody resultMap = new DefaultResponseBody();
        resultMap.setCode(201);
        resultMap.setMessage("首页展示成功");
        HashMap<String, Object> map = new HashMap<>();
        Pager<TransRequest> pager = transRequestService.findByPager(pageNum, pageSize);
        map.put("requests", pager.getRows());
        map.put("count", pager.getTotal());
        resultMap.setData(map);
        return resultMap;
    }
}
